package com.wh.springbootshiro.realm;

import com.wh.springbootshiro.pojo.User;
import com.wh.springbootshiro.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * @Auther: HuiEr
 * @Date: 2020/3/3 17:44
 * @Description
 */
public class MyRealm extends AuthorizingRealm {
    private Logger logger= LoggerFactory.getLogger(MyRealm.class);
    @Autowired
    private IUserService userService;
    @Override
    public String getName() {
        return "MyRealm";
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
       logger.info("这里是授权realm。。。。。。");

        String user=(String)principalCollection.getPrimaryPrincipal();
        HashSet<String> roles = new HashSet<>();
        HashSet<String> permissions = new HashSet<String>();
        roles.add("seller");
        permissions.add("ad:add");
        permissions.add("user:add");

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(roles);
        simpleAuthorizationInfo.setStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.info("这里是认证realm。。。。。。。");
        String username= (String)authenticationToken.getPrincipal();
        User user=null;
        try{
            user = userService.findUserByName(username);
        }catch (Exception err){
            logger.info("调用dao的接口出错"+err.fillInStackTrace());
        }
        if (null==user){
            return null;
        }
/*
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes("abc"), getName());
*/
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,user.getPassword(), ByteSource.Util.bytes("abc"), getName());
        return simpleAuthenticationInfo;
    }
}
